// 确保DOM完全加载后再执行代码
document.addEventListener('DOMContentLoaded', function() {
    // 检查jQuery是否可用，如果不可用则使用原生JS替代
    const $ = window.jQuery || function(selector) {
        return {
            val: function() {
                return document.querySelector(selector).value;
            },
            on: function(event, handler) {
                document.querySelector(selector).addEventListener(event, handler);
            },
            // 添加其他必要的方法...
        };
    };

    // 在筛选路线时只显示已批准的路线
    function filterHikes() {
        // 使用兼容性写法获取值
        const province = document.getElementById('provinceSelect')?.value || '';
        const level = document.getElementById('levelSelect')?.value || '';
        const search = document.getElementById('route-search')?.value.trim().toLowerCase() || '';

        // 显示加载状态
        showLoading(true);
        clearError();

        // 使用fetch API替代$.get
        fetch(`/api/hikes?province=${encodeURIComponent(province)}&level=${encodeURIComponent(level)}&search=${encodeURIComponent(search)}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(data => {
                if(data.success) {
                    // 只显示已批准的路线
                    const approvedHikes = data.data.filter(hike => hike.status === 'approved');
                    renderHikes(approvedHikes);
                } else {
                    showError(data.error || '获取数据失败');
                }
            })
            .catch(error => {
                showError('请求失败: ' + error.message);
                console.error('Error:', error);
            })
            .finally(() => {
                showLoading(false);
            });
    }

    // 显示/隐藏加载指示器
    function showLoading(show) {
        const loadingIndicator = document.querySelector('.loading-indicator');
        if (loadingIndicator) {
            loadingIndicator.style.display = show ? 'flex' : 'none';
        }
    }

    // 显示错误信息
    function showError(message) {
        const errorMessage = document.querySelector('.error-message');
        if (errorMessage) {
            errorMessage.textContent = message;
            errorMessage.style.display = 'block';
        }
    }

    // 清除错误信息
    function clearError() {
        const errorMessage = document.querySelector('.error-message');
        if (errorMessage) {
            errorMessage.style.display = 'none';
        }
    }

    // 渲染路线列表
    function renderHikes(hikes) {
        const hikesContainer = document.querySelector('.hike-grid');
        if (!hikesContainer) return;

        // 清空现有内容
        hikesContainer.innerHTML = '';

        // 如果没有结果，显示提示信息
        if (!hikes || hikes.length === 0) {
            hikesContainer.innerHTML = '<div class="no-results">没有找到匹配的徒步路线</div>';
            return;
        }

        // 渲染每条路线
        hikes.forEach(hike => {
            const hikeCard = document.createElement('div');
            hikeCard.className = 'hike-card';

            // 生成评分星星
            const score = parseFloat(hike.score) || 0;
            const stars = Array.from({length: 5}, (_, i) =>
                `<svg class="star ${i < Math.floor(score) ? 'filled' : ''}" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
                </svg>`
            ).join('');

            hikeCard.innerHTML = `
                <div class="card-image">
                    <img src="${hike.image ? '/static/images/' + hike.image : '/static/images/default-hike.jpg'}"
                         alt="${hike.name || '未命名路线'}" loading="lazy">
                    <div class="image-overlay"></div>
                    <span class="difficulty-tag ${(hike.difficulty || '').toLowerCase()}">${hike.difficulty || '未知'}</span>
                    <button class="save-btn">
                        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"></path>
                        </svg>
                    </button>
                </div>
                <div class="card-content">
                    <div class="card-header">
                        <h3 class="hike-name">${hike.name || '未命名路线'}</h3>
                        <div class="rating">
                            ${stars}
                            <span>${score.toFixed(1)}</span>
                        </div>
                    </div>
                    <p class="location">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path>
                            <circle cx="12" cy="10" r="3"></circle>
                        </svg>
                        ${hike.address || '未知地区'}
                    </p>
                    <div class="card-stats">
                        <div class="stat">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <path d="M3 3v18h18"></path>
                                <path d="M18.7 8l-5.1 5.2-2.8-2.7L7 14.3"></path>
                            </svg>
                            <span class="hike-length">${hike.length || '0'} km</span>
                        </div>
                        <div class="stat">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <circle cx="12" cy="12" r="10"></circle>
                                <polyline points="12 6 12 12 16 14"></polyline>
                            </svg>
                            <span>${hike.duration || '0'}小时</span>
                        </div>
                        <div class="stat">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
                                <line x1="16" y1="2" x2="16" y2="6"></line>
                                <line x1="8" y1="2" x2="8" y2="6"></line>
                                <line x1="3" y1="10" x2="21" y2="10"></line>
                            </svg>
                            <span class="hike-best_time">${hike.best_time || '全年'}</span>
                        </div>
                    </div>
                    <a href="/hike/${hike.id || '#'}" class="explore-btn">
                        探索路线
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M5 12h14"></path>
                            <path d="M12 5l7 7-7 7"></path>
                        </svg>
                    </a>
                </div>
            `;

            // 添加动画延迟效果
            hikeCard.style.animationDelay = `${Math.random() * 0.5}s`;
            hikesContainer.appendChild(hikeCard);
        });
    }

    // 初始化筛选表单事件
    function initFilterForms() {
        const provinceSelect = document.getElementById('provinceSelect');
        const levelSelect = document.getElementById('levelSelect');

        // 省份选择变化事件
        if (provinceSelect) {
            provinceSelect.addEventListener('change', function() {
                filterHikes();
            });
        }

        // 难度选择变化事件
        if (levelSelect) {
            levelSelect.addEventListener('change', function() {
                filterHikes();
            });
        }
    }

    // 初始化搜索功能
    function initSearch() {
        const searchInput = document.getElementById('route-search');
        const searchBtn = document.getElementById('search');

        if (!searchInput || !searchBtn) return;

        // 点击查询按钮触发搜索
        searchBtn.addEventListener('click', function() {
            filterHikes();
        });

        // 回车键也可以触发搜索
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                filterHikes();
            }
        });
    }

    // 初始化重置功能
    function initReset() {
        const resetBtn = document.getElementById('reset');
        if (!resetBtn) return;

        resetBtn.addEventListener('click', function() {
            // 重置表单值
            const provinceSelect = document.getElementById('provinceSelect');
            const levelSelect = document.getElementById('levelSelect');
            const searchInput = document.getElementById('route-search');

            if (provinceSelect) provinceSelect.value = '';
            if (levelSelect) levelSelect.value = '';
            if (searchInput) searchInput.value = '';

            // 重新加载所有路线
            filterHikes();
        });
    }

        // 新增：初始化路线审核功能
    function initHikeReview() {
        // 使用事件委托处理动态生成的按钮
        document.addEventListener('click', function(e) {
            // 处理路线批准/拒绝
            if (e.target.classList.contains('btn-approve') ||
                e.target.classList.contains('btn-reject')) {

                const button = e.target;
                const hikeId = button.getAttribute('data-hike-id');
                const action = button.classList.contains('btn-approve') ? 'approve' : 'reject';

                if (!hikeId) {
                    console.error('缺少路线ID');
                    return;
                }

                // 显示加载状态
                const originalText = button.textContent;
                button.disabled = true;
                button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 处理中...';

                // 获取CSRF令牌
                const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content || '';

                fetch(`/admin/hike/${hikeId}/${action}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest',
//                        'X-CSRFToken': csrfToken
                    },
                    credentials: 'same-origin'
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        // 显示成功消息并刷新
                        showFlashMessage(data.message || '操作成功', 'success');
                        setTimeout(() => location.reload(), 1000);
                    } else {
                        throw new Error(data.message || '操作失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showFlashMessage(error.message, 'error');
                    button.disabled = false;
                    button.innerHTML = originalText;
                });
            }
        });
    }

    // 新增：显示浮动消息
    function showFlashMessage(message, type) {
        // 移除现有的消息
        const existingFlash = document.querySelector('.flash-message');
        if (existingFlash) {
            existingFlash.remove();
        }

        const flashDiv = document.createElement('div');
        flashDiv.className = `flash-message ${type}`;
        flashDiv.textContent = message;
        document.body.appendChild(flashDiv);

        // 自动消失
        setTimeout(() => {
            flashDiv.classList.add('fade-out');
            setTimeout(() => flashDiv.remove(), 500);
        }, 3000);
    }


    // 广播功能
    function initAnnouncements() {
    // 广播切换
    const announcementItems = document.querySelectorAll('.announcement-item');
    const prevBtn = document.querySelector('.announcement-prev');
    const nextBtn = document.querySelector('.announcement-next');
    let currentIndex = 0;

    function showAnnouncement(index) {
        announcementItems.forEach(item => item.classList.remove('active'));
        announcementItems[index].classList.add('active');
        currentIndex = index;
    }


    if (prevBtn && nextBtn && announcementItems.length > 1) {
        prevBtn.addEventListener('click', () => {
            let newIndex = currentIndex - 1;
            if (newIndex < 0) newIndex = announcementItems.length - 1;
            showAnnouncement(newIndex);
        });

        nextBtn.addEventListener('click', () => {
            let newIndex = currentIndex + 1;
            if (newIndex >= announcementItems.length) newIndex = 0;
            showAnnouncement(newIndex);
        });

        // 自动轮播
        let autoScroll = setInterval(() => {
            let newIndex = currentIndex + 1;
            if (newIndex >= announcementItems.length) newIndex = 0;
            showAnnouncement(newIndex);
        }, 5000);

        // 鼠标悬停时暂停轮播
        const announcementContainer = document.querySelector('.announcement-container');
        if (announcementContainer) {
            announcementContainer.addEventListener('mouseenter', () => {
                clearInterval(autoScroll);
            });

            announcementContainer.addEventListener('mouseleave', () => {
                autoScroll = setInterval(() => {
                    let newIndex = currentIndex + 1;
                    if (newIndex >= announcementItems.length) newIndex = 0;
                    showAnnouncement(newIndex);
                }, 5000);
            });
        }
    }

    // 管理员功能
    if (document.querySelector('#newAnnouncementForm')) {
        const form = document.querySelector('#newAnnouncementForm');
        form.addEventListener('submit', function(e) {
            e.preventDefault();

            const formData = new FormData(form);
            fetch('/api/announcements', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
//                    'X-CSRFToken': document.querySelector('meta[name="csrf-token"]')?.content || ''
                },
                body: JSON.stringify({
                    title: formData.get('title'),
                    content: formData.get('content')
                })
            })
            .then(async response => {
                const data = await response.json();
                if (!response.ok) {
                    throw new Error(data.message || '发布失败');
                }
                return data;
            })
            .then(data => {
                if (data.success) location.reload();
            })
            .catch(error => {
                console.error('Error:', error);
                alert(error.message);
            });
        });
    }

    // 删除公告
    document.querySelectorAll('.announcement-delete').forEach(btn => {
        btn.addEventListener('click', function() {
            if (!confirm('确定要删除这条公告吗？')) return;

            const announcementId = this.getAttribute('data-id');
            fetch(`/api/announcements/${announcementId}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
//                    'X-CSRFToken': document.querySelector('meta[name="csrf-token"]')?.content || ''
                }
            })
            .then(async response => {
                const data = await response.json();
                if (!response.ok) {
                    throw new Error(data.message || '删除失败');
                }
                return data;
            })
            .then(data => {
                if (data.success) location.reload();
            })
            .catch(error => {
                console.error('Error:', error);
                alert(error.message);
            });
        });
    });
}

// 确保DOM加载后执行
document.addEventListener('DOMContentLoaded', initAnnouncements);


    // 初始化所有功能
    function initAll() {
        initFilterForms();
        initSearch();
        initReset();
        initHikeReview(); // 新增初始化路线审核功能
        initAnnouncements(); // 新增初始化广播功能
        filterHikes();
    }

initAll();


    // 卡片悬停效果
    document.querySelectorAll('.hike-card').forEach(card => {
        card.addEventListener('mousemove', (e) => {
            const x = e.pageX - card.offsetLeft;
            const y = e.pageY - card.offsetTop;

            const centerX = card.offsetWidth / 2;
            const centerY = card.offsetHeight / 2;

            const angleX = (y - centerY) / 10;
            const angleY = (centerX - x) / 10;

            card.style.transform = `perspective(1000px) rotateX(${angleX}deg) rotateY(${angleY}deg)`;
        });

        card.addEventListener('mouseleave', () => {
            card.style.transform = 'perspective(1000px) rotateX(0) rotateY(0)';
        });
    });

    // 图片懒加载和渐显效果
    const lazyImages = document.querySelectorAll('img[loading="lazy"]');
    const imageObserver = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const img = entry.target;
                img.style.opacity = 0;
                img.style.transition = 'opacity 0.6s ease';
                img.onload = () => {
                    img.style.opacity = 1;
                };
                if (img.dataset.src) {
                    img.src = img.dataset.src;
                }
                imageObserver.unobserve(img);
            }
        });
    }, { threshold: 0.1 });

    lazyImages.forEach(img => imageObserver.observe(img));
});
